var express = require('express')
var router = express.Router()
const { formatResponse } = require('../utils/tool')
const { ValidationError } = require('../utils/errors')
const { getCaptchaService } = require('../service/captchaService')

// 登录
router.get('/', async function (req, res, next) {
  // 生成一个验证码
  const captcha = await getCaptchaService()
  req.session.captcha = captcha.text
  // 设置响应头
  res.setHeader('Content-Type', 'image/svg+xml')
  res.send(captcha.data)
})
router.post('/', async function (req, res, next) {
  if (req.body.captcha.toString().toLowerCase() !== req.session.captcha.toLowerCase()) {
    // 如果进入此 if，说明是有问题的，用户输入的验证码不正确
    // res.send(formatResponse(0, '', {msg:"验证码错误",code:406}))
    throw new ValidationError('验证码错误2')
  }
  res.send(formatResponse(0, '', {msg:"验证通过",code:0}))
})

module.exports = router
